package com.example.myblog_sm.controller;

import com.example.myblog_sm.common.AppVar;
import com.example.myblog_sm.common.PassWordUtils;
import com.example.myblog_sm.common.Result;
import com.example.myblog_sm.model.Userinfo;
import com.example.myblog_sm.model.Vo.UserinfoVo;
import com.example.myblog_sm.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/user")
public class UserController {
    /**
     * 注册功能
     * 返回统一对象
     * @param userinfo
     * @return
     */
    @Autowired
    private UserService userService;
    @RequestMapping("/reg")
    public Result reg(Userinfo userinfo){
        //1.参数效验
        if(userinfo == null || !StringUtils.hasLength(userinfo.getUsername()) ||
                !StringUtils.hasLength(userinfo.getPassword())){
            return Result.fail(-1,"参数异常");

        }
        userinfo.setPassword(PassWordUtils.encrypt(userinfo.getPassword()));
        //2.请求service层进行添加操作
        int res = userService.reg(userinfo);
        //3.将执行的结果返回给前端
        return Result.succ(res);
    }
    @RequestMapping("/login")
    public Result login(UserinfoVo userinfoVo, HttpServletRequest request){
        //1.参数效验
        if(userinfoVo == null || !StringUtils.hasLength(userinfoVo.getUsername())||
                !StringUtils.hasLength(userinfoVo.getPassword())){
            //非法用户
            return Result.fail(-1,"参数有问题");

        }
        //2.根据用户名查询对象
        Userinfo userinfo = userService.getUserByName(userinfoVo.getUsername());
        if( userinfo == null|| userinfo.getId() == 0){
            //不存在此用户
            return Result.fail(-2,"用户名或者密码错误");
        }
        //3.使用对象中的密码和用户输入的密码进行比较!
        // userinfoVo.getPassword().equals(userinfo.getPassword())
        if(!PassWordUtils.decrypt(userinfoVo.getPassword(),userinfo.getPassword())){
            return Result.fail(-2,"用户名或者密码错误");
        }
        //4.比较成功，对象存储到session中
        HttpSession session = request.getSession();
        session.setAttribute(AppVar.SESSION_USERINFO_KEY,userinfo);
        //5.结果返回给用户
        return Result.succ(1);
    }
    @RequestMapping("/logout")
    public Result logout(HttpServletRequest request){
        //在session中获取用户信息,参数为false默认有就返回用户信息，没有就返回null
        HttpSession session = request.getSession(false);
        if(session != null &&  session.getAttribute(AppVar.SESSION_USERINFO_KEY) != null){
            session.removeAttribute(AppVar.SESSION_USERINFO_KEY);
        }
        return Result.succ(1);
    }

}
